<?php
header('Content-Type: application/json');
require('config.php');
require('functions.php');
require('facebooksdk/src/facebook.php');
requireAuth();

$msgs = $_POST['msg'];
$urls = $_POST['url'];
$pages = $_POST['pages'];
$interval = intval($_POST['interval']) * 3600;

$arrUrl = explode("\n", $urls);
$arrMsg = explode("\n", $msgs);

if(!empty($pages)){
	$totalPost = count($pages) * count($arrUrl);
	if($totalPost > FB_BATCH_REQ_LIMIT){
		echo json_encode(array('error' => 1, 'msg' => 'Maximum post limit reached. Make sure the number of posts less than ' . FB_BATCH_REQ_LIMIT));
		exit(0);
	}
	$facebook = new Facebook($fbconfig);
	$arrPageId = array();
	$responseId = array();
	$data = array();
	$arrBatch = array();
	$dbParam = array();
	$name = null;
	$picture = null;
	$caption = null;
	$desc = null;
	if(!isset($_SESSION['cs_user_pages']) && empty($_SESSION['cs_user_pages'])){
		echo json_encode(array('error' => 1, 'msg' => 'You don\'t have any facebook fan page.'));
		exit(0);
	}
	foreach($pages as $fbPageId){
		if(!array_key_exists($fbPageId, $_SESSION['cs_user_pages'])){
			array_push($arrBatch, null);
			continue;
		}
		array_push($arrPageId, $fbPageId);
		$apiUrl = pagePostApiUrl($fbPageId);

		try{
			$pageInfo = getTokenByFbPageId($fbPageId);
			$token = $pageInfo['token'];
			$pageId = $pageInfo['page_id'];
			$i = 0;
			$published = 1;
			$sdate = strtotime(cleanValue($_POST['sdate']));
			
			foreach($arrUrl as $url){
				// is schedule?
				if($sdate - time() > 600){
					$published = 0;
				}
				else{
					$published = 1;
				}

				$arrMsg[$i] = (isset($arrMsg[$i]) && $arrMsg[$i] != 'NULL') ? $arrMsg[$i] : '';
				$body = array(
					'access_token' => $token,
					'message' => $arrMsg[$i],
					'link' => $url,
					'published' => $published
				);
				if(!$published){
					$body['scheduled_publish_time'] = $sdate;
				}

				array_push($arrBatch, array(
					"method" => "POST",
					"relative_url" => $apiUrl,
					"body" => http_build_query($body)
				));
				$params = array(
						'post_name' => $name,
						'post_url' => $url,
						'post_message' => $arrMsg[$i],
						'post_picture' => $picture,
						'post_caption' => $caption,
						'post_desc' => $desc,
						'post_fb_id' => null,
						'page_id' => $pageId,
						'post_from_bulk' => 1,
						'post_publish_time' => date('Y/m/d H:i:s', $sdate),
						'user_id' => $userId
					);
				array_push($dbParam, $params);
				$sdate += $interval;
				$i++;
			}
		}
		catch(Exception $e){
			echo json_encode(array('error' => 1, 'msg' => $e->getMessage()));
			exit(0);
		}
	}
	try{
		$response = $facebook->api(_FB_API_VERSION . '/', "POST", array('batch' => json_encode($arrBatch)));
		if(is_array($response) && !empty($response)){
			$i = 0;
			foreach($response as $res){
				if($res['code'] == 200 && isset($res['body'])){
					$body = json_decode($res['body'], true);
					array_push($responseId, $body['id']);
					// save to DB
					$dbParam[$i]['post_fb_id'] = $body['id'];
					insertPagePost($dbParam[$i]);
				}
				else{
					if(isset($res['body'])){
						array_push($responseId, $res['body']);
					}
					else{
						array_push($responseId, null);
					}
				}
				$i++;
			}
		}
	}
	catch(Exception $e){
		echo json_encode(array('error' => 1, 'msg' => $e->getMessage()));
		exit(0);
	}
	echo json_encode($responseId);
}